package com.liuwei.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Slf4j
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 判断有客户端上线,将此客户端的消息广播给其他客户端
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String message = "客户端-" + channel.remoteAddress() + "于" + LocalDateTime.now().format(formatter) + "上线了\n";
        log.info(message);

        // 得到其他用户的channel,向其他客户端发送此客户端上线的消息
        channelGroup.writeAndFlush(message);
        // 加入到channelGroup
        channelGroup.add(channel);
    }

    // 判断有客户端下线,就把下线消息广播给其他客户端
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String message = "客户端-" + channel.remoteAddress() + "下线了\n";
        log.info(message);
        // 广播给其他客户端
        channelGroup.writeAndFlush(message);
    }

    // 具体读数据的消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 获得当前发消息的channel
        Channel channel = ctx.channel();
        // 遍历所有channel
        channelGroup.forEach(ch -> {
            // 向其他客户端发
            if (ch != channel) {
                ch.writeAndFlush("客户端-" + channel.remoteAddress() + "于" + LocalDateTime.now().format(formatter) + "说:"
                + msg + "\n"+"CR7");
            } else {
                // 向自己发
                ch.writeAndFlush("我自己-" + channel.remoteAddress() + "于" + LocalDateTime.now().format(formatter) + "向自己说:"
                        + msg + "\n"+"CR7");
            }
        });
    }

    // 重写处理异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage());
        ctx.close();
    }
}
